/*
 * Copyright (C) 2008-2011 CBDP Consortium
 * 
 * All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.
 * 
 * This software consists of contributions made by many individuals, 
 * listed below:
 *
 * Author: 	Xabier Laiseca <xabier.laiseca@deusto.es>
 * 			David Ausín <david.ausin@deusto.es>
 */
package cbdp.server.contextreasoner.activator;

import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

import cbdp.server.contextreasoner.ContextManager;
import cbdp.server.contextreasoner.ContextManagerWithoutExecutionSupport;
import cbdp.server.contextreasoner.Reasoner;
import cbdp.server.contextreasoner.impl.creator.ServiceCreator;
import cbdp.server.contextreasoner.impl.reasoner.GenericReasoner;
import cbdp.server.contextreasoner.internal.InternalContextManager;
import cbdp.server.contextreasoner.internal.OntologyContainer;

/**
 * @author  Xabier Laiseca
 */
public class Activator implements BundleActivator
{
	private OntologyContainer ontologyContainer;
	
	private InternalContextManager contextManager;
	private ServiceRegistration contextManagerRegistration;
	
	private GenericReasoner reasoner;
	private ServiceRegistration reasonerRegistration;
	
	
	public void start(final BundleContext context) throws Exception
	{		
		final ServiceCreator serviceCreator = new ServiceCreator();
		serviceCreator.createServices(context);
		
		ontologyContainer = serviceCreator.getOntologyContainer();
		
		contextManager = serviceCreator.getContextManager();
		reasoner = serviceCreator.getGenericReasoner();
		
		final Hashtable<String, Object> properties = new Hashtable<String, Object>();
		properties.put(ContextManagerWithoutExecutionSupport.CONTEXT_MANAGER_NAME_PROPERTY_NAME, serviceCreator.getConfiguration().getStorageType().toString());
		properties.put(ContextManagerWithoutExecutionSupport.CONTEXT_MANAGER_SUPPORTS_TRANSACTIONS_PROPERTY_NAME, supportsTransactions());
		
		contextManagerRegistration = context.registerService(ContextManager.class.getName(), contextManager, properties);
		
		reasonerRegistration = context.registerService(Reasoner.class.getName(), reasoner, null);
	}

	private boolean supportsTransactions()
	{
		return ontologyContainer.getOntModel().supportsTransactions();
	}

	public void stop(final BundleContext context) throws Exception
	{
		contextManagerRegistration.unregister();
		contextManagerRegistration = null;
		
		reasonerRegistration.unregister();
		reasonerRegistration = null;
		
		contextManager.unload();
		reasoner.unload();
		
		ontologyContainer.close();
		
		contextManager = null;
		reasoner = null;
		ontologyContainer = null;
	}
}
